<template>
  <!-- 自身的index      selfIndex -->
  <!-- 当前的index      currenIndex -->
  <!-- transition     vue独有的动画标签 -->
  <transition>
    <div class="car-item" v-if="selfIndex == currentIndex">
      <slot></slot>
    </div>
  </transition>
</template>
 <script>
/* getCurrentInstance获取当前实例 */
import { getCurrentInstance, reactive, toRefs, watch } from "vue";

export default {
  name: "CarItem" /* 组件的名字 */,
  setup(props) {
    /* 定义一个常量保存这个实例 */
    const instance = getCurrentInstance();
    /* 打印  当前组件的每一个实例     vNode虚拟节点    里面的key值对应实例的下标 */
    const data = reactive({
      selfIndex: instance.vnode.key,
      currentIndex: instance.parent.ctx.currentIndex,
    });
    watch(
      () => {
        return instance.parent.ctx.currentIndex;
      },
      (value) => {
        data.currentIndex = value;
      }
    );
    return { ...toRefs(data) };
  },
};
</script>
<style lang="scss">
.car-item {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}
img {
  width: 100%;
  height: 100%;
}
/* 进入和离开之前 */
.v-enter-active,
.v-leave-active {
  transition: opacity 0.5s linear;
}
/* 定义进入过渡生效时的状态 */
.v-enter-active {
  opacity: 0;
}
/* 定义进入过渡的结束状态 */
.v-enter-to {
  opacity: 1;
}
/* 定义离开过渡的开始状态 */
.v-leave-active {
  opacity: 1;
}
/* 定义离开过渡的结束状态 */
.v-leave-to {
  opacity: 0;
}
</style>